// 我们经常需要做一些营销活动，会涉及到很多的商品。
// 现在有2个商品Product1和Product2，他们的一天内促销周期以二维数组存储
// 如：[['0300', '0312'], ['0614', '0714']]
// 促销周期数组内的每个子数组代表开始的日期（时分）和结束日期，24小时计时法
// 如：['0300', '0312']代表其3点00分开始，3点12分结束。
// 需求你求出2个商品同时参加营销的时间段是什么
// Input:
// Product1 sales time slot  = [['0709', '0720'], ['0108', '0120'], ['1512','1612']],
// Product 2 sales time slot = [['0300', '0312'], ['0614', '0714']],
// Output: ['0709', '0714']
const p1slot = [['0709', '0720'], ['0108', '0120'], ['1512','1612']];
const p2slot = [['0300', '0312'], ['0614', '0714'], ['1518','1628']];
const getCommonPeriod = (slot1, slot2)=> {
    const res = []
    for(let i = 0; i < slot1.length; i++) {
        for(let j = 0; j < slot2.length; j++) {
            if(slot2[j][0] > slot1[i][0] && slot2[j][0] < slot1[i][1]) {
                res.push([slot2[j][0], slot1[i][1]])
            }
            if(slot2[j][1] > slot1[i][0] && slot2[j][0] < slot1[i][0]) {
                res.push([slot1[i][0], slot2[j][1]])
            }
        }
    }
    return res
}
console.log(getCommonPeriod(p1slot, p2slot)) //[['0709', '0714']]

function findCommonTimeSlot(product1, product2) {
    const timeToMinutes = (timeStr) => {
      const hour = parseInt(timeStr.slice(0, 2));
      const minute = parseInt(timeStr.slice(2));
      return hour * 60 + minute;
    };
  
    const commonTimeSlot = [];
    for (const slot1 of product1) {
      for (const slot2 of product2) {
        const start1 = timeToMinutes(slot1[0]);
        const end1 = timeToMinutes(slot1[1]);
        const start2 = timeToMinutes(slot2[0]);
        const end2 = timeToMinutes(slot2[1]);
  
        if (start1 <= end2 && end1 >= start2) {
          // 有重叠时间段
          const commonStart = Math.max(start1, start2);
          const commonEnd = Math.min(end1, end2);
          commonTimeSlot.push([commonStart, commonEnd]);
        }
      }
    }
  
    if (commonTimeSlot.length === 0) {
      return null;
    } else {
      // 将最终结果转换为字符串格式
      return commonTimeSlot[0].map((slot) => {
        const hour = String(Math.floor(slot / 60)).padStart(2, '0');
        const minute = String(slot % 60).padStart(2, '0');
        return hour + minute;
      });
    }
  }
  
  console.log(findCommonTimeSlot(p1slot, p2slot));